/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.web;

import com.sfkj.walk.aliyun.oss.AliyunOssService;
import com.sfkj.walk.aliyun.oss.UploadFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@RestController
public class OssController {
    private static final String AVARAT = "avatar";
    private static final String NOTE = "note";
    private static final String ACTIVITY = "activity";

    private final AliyunOssService aliyunOssService;

    @GetMapping("/image")
    public void image(String name, HttpServletResponse response) throws IOException {
        UploadFile file = aliyunOssService.getFile(name);

        response.setContentType(file.getContentType());
        response.setContentLengthLong(file.getSize());
        // Flush byte array to servlet output stream.
        ServletOutputStream out = response.getOutputStream();
        out.write(file.getBytes());
        out.flush();
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {
        UploadFile file = aliyunOssService.getFile(name);

        response.setContentType(file.getContentType());
        response.setContentLengthLong(file.getSize());
        response.setHeader("Content-disposition", file.getContentDisposition());
        // Flush byte array to servlet output stream.
        ServletOutputStream out = response.getOutputStream();
        out.write(file.getBytes());
        out.flush();
    }

}
